package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class DisplayMessageActivity extends AppCompatActivity {
  public final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 0;

  private TextView tv2;

  static int flag = 0;
  static int clickCount = 0;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);

    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    TextView textView = findViewById(R.id.textView);
    textView.setText(message + (++flag));
    tv2 = findViewById(R.id.textView2);
    // check the WRITE_CALENDAR permission
    if (Tools.permissionIsTrue(ContextCompat.checkSelfPermission(this,
      Manifest.permission.WRITE_CALENDAR))) {
      tv2.setText("hello world");
    } else {
      tv2.setText("new permission check");
    }

    /**
     * 检查是否有对应权限
     * 是否需要说明理由
     * 请求该权限
     */
    if (!Tools.permissionIsTrue(ContextCompat.checkSelfPermission(this,
      Manifest.permission.READ_CONTACTS))) {
      if (ActivityCompat.shouldShowRequestPermissionRationale(this,
        Manifest.permission.READ_CONTACTS)) {
        // 之前被拒绝过一次，需要解释为何需要这个权限
        tv2.setText("需要读取联系人信息");
      } else {
        // 请求这个权限 this is a async will call onRequestPermissionResult
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS},
          MY_PERMISSIONS_REQUEST_READ_CONTACTS);
      }
    } else {
      // 用户已经同意
      tv2.setText("已同意");
    }
    ViewGroup viewGroup = findViewById(R.id.displayMessage);
    System.out.println("second create: width: " + viewGroup.getMeasuredWidth() + " height: " + viewGroup.getMeasuredHeight());
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                         @NonNull int[] grantResults) {
    switch (requestCode) {
      case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
        if (grantResults.length > 0 && Tools.permissionIsTrue(grantResults[0])) {
          tv2.setText("callback: user granted.");
        } else {
          tv2.setText("callback: user denied.");
        }
        break;
    }
  }

  @Override
  protected void onStart() {
    super.onStart();
    System.out.println("second start");
  }

  @Override
  protected void onRestart() {
    super.onRestart();
    System.out.println("second restart");
  }

  @Override
  protected void onResume() {
    super.onResume();
    String message = getIntent().getStringExtra(MainActivity.EXTRA_MESSAGE);
    Tools.log(this, message + " flag " + flag + " click count: " + clickCount);
    View view = findViewById(R.id.displayMessage);
    System.out.println("second resume: width: " + view.getMeasuredWidth() + " height: " + view.getMeasuredHeight());
  }

  @Override
  protected void onPause() {
    super.onPause();
    System.out.println("second pause");
  }

  @Override
  protected void onStop() {
    super.onStop();
    System.out.println("second stop");
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    System.out.println("second destroy");
  }

  public void reopen(View view) {
    clickCount++;
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    intent.putExtra(MainActivity.EXTRA_MESSAGE, "reopen");
    //    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
  }

  public void openBrowser(View view) {
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.v2ex.com"));
    //    Intent intent = alwaysChooser();
    if (intentCanBeHandle(intent)) {
      startActivity(intent);
    }
  }

  public void openMail(View v) {
    Intent intent = sendMail();
    if (intentCanBeHandle(intent)) {
      startActivity(intent);
    }
  }

  public Intent sendMail() {
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    // The intent does not have a URI, so declare the "text/plain" MIME type
    emailIntent.setType("application/email");
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"jon@example.com"}); // recipients
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email subject");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message text");
    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://path/to/email/attachment"));
    // You can also attach multiple items by passing an ArrayList of Uris
    return Intent.createChooser(emailIntent,
      getResources().getString(R.string.button_open_browser));
    //    return emailIntent;
  }

  public Intent phoneCall() {
    return new Intent(Intent.ACTION_DIAL, Uri.parse("tel:12345"));
  }

  private boolean intentCanBeHandle(Intent intent) {
    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent,
      PackageManager.MATCH_DEFAULT_ONLY);
    Tools.log(this, list.size());
    return !list.isEmpty();
  }

  public Intent alwaysChooser() {
    Intent intent = Intent.createChooser(new Intent(Intent.ACTION_SEND),
      ((TextView) findViewById(R.id.textView)).getText().toString());
    return intent;
  }

  public void openMap(View v) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse("geo:33.331701,120.15898?z=11"));
    if (intent.resolveActivity(getPackageManager()) != null) {
      startActivity(intent);
    }
  }
}
